public without sharing class NoContractAttachmentController {
    
    public String msg {get ;private set;}
    public String backId {get; private set;}
    public Boolean isSuccess {get; private set;}

    public  Integer rptN {get; private set; }
    private NoContractInstrumentApplicationDetail__c noc ;
    public String rename {get;set;}//附件重命名


    public NoContractAttachmentController() {

        backId = System.currentPageReference().getParameters().get('id');

    }
    public void init(){
    	rptN = [select count() from Attachment where ParentId = :backId and Name like '%仪器签收确认单%'];

    	noc = [select Id,InstrumentConfirmation__c from NoContractInstrumentApplicationDetail__c where Id =:backId ];

    }


    public void save(){
        msg = '';
        SavePoint sp = Database.setSavePoint();
    	try{
           String s = System.currentPageReference().getParameters().get('fileValue');
           Blob body = s != null ?EncodingUtil.base64Decode(s.substring(s.indexOf(',')+1) ) : null;
           String format = System.currentPageReference().getParameters().get('fileFormat');
           System.debug('***'+rptN +'-->' + s);
           if((s == null || s == '') && rptN == 0){
                msg = '请将上传文件名称重命名为“XXX的XXX仪器签收确认单”的文件名，如：“四川省华西医院的IS1200仪器签收确认单”的命名方式。若格式命名错误，会导致上传无效！';
                return ;
            }
           String attName = null;
            if(String.isBlank(rename) == false){
                attName = rename +'.'+ format;
            }else{
                attName = System.currentPageReference().getParameters().get('fileName') +'.'+ format;
            }

            if(body != null && s.length() > 0 ){
              Attachment att = new Attachment();
              att.Name = attName;
              att.Body = body;
              att.ParentId = backId;
              insert att;
            }
        	
          	//System.debug(body.toString());
            integer j= 0;
            for(Attachment at :[select Id,Name from Attachment where ParentId = :backId]){
                 if(String.valueOf(at.Name).contains('仪器签收确认单')){
                 	j++;
                 }
           	}
           noc.InstrumentConfirmation__c = j;
           update noc ;
           msg = '保存成功!';
           isSuccess = true;/**/
        }catch(Exception e){
          Database.rollback(sp);
          msg = '保存失败'+e.getMessage();
         //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,e.getMessage()));
        }
        
    }
}